#include "localconfig.h"

LocalConfig::LocalConfig(QObject *parent): QObject(parent){
    m_logFile.setFileName("clipboard.log");
    if(m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) {
        m_stream.setDevice(&m_logFile);
    }
}

QString LocalConfig::readLocalConfig(QString name){
    QString fileName = "config.ini";
    QSettings settings(fileName, QSettings::IniFormat);

    // 读取设置
    settings.beginGroup("General");
    QString  readedString= settings.value(name).toString();
    settings.endGroup();
    return readedString;
}

bool LocalConfig::writeLocalConfig(QString name,QString value){
    QString fileName = "config.ini";
    QSettings settings(fileName, QSettings::IniFormat);

    // 写入设置
    settings.beginGroup("General");
    settings.setValue(name, value);
    settings.endGroup();
    return true;
}

void LocalConfig::log(const QString &message)
{
    if(m_logFile.isOpen()) {
        m_stream << QDateTime::currentDateTime().toString(Qt::ISODate)
        << " - " << message << Qt::endl;
        m_stream.flush();
    }
}

QString LocalConfig::xorEncryptDecrypt(const QString &data, char key) {
    QString result;
    for (int i = 0; i < data.size(); ++i) {
        char encryptedChar = data.at(i).toLatin1() ^ key;
        result.append(QChar::fromLatin1(encryptedChar));
    }
    return result;
}

void LocalConfig::encryptedIniOperation() {
    const char encryptionKey = 0x55; // 简单的加密密钥

    // 写入加密数据
    QSettings settings("secure_config.ini", QSettings::IniFormat);
    QString originalPwd = "mypassword123";
    QString encryptedPwd = xorEncryptDecrypt(originalPwd, encryptionKey);
    settings.setValue("Security/encryptedPassword", encryptedPwd);

    // 读取并解密数据
    QString readEncryptedPwd = settings.value("Security/encryptedPassword").toString();
    QString decryptedPwd = xorEncryptDecrypt(readEncryptedPwd, encryptionKey);
    //qDebug() << "Decrypted Password:" << decryptedPwd;
}
